<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="140px">
        <EditDropDown dropdownTitle="盘点基本信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="盘点名称" prop="takeStockName">
                  <px-input v-model="formValue.takeStockName" placeholder="请输入盘点名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点编码" prop="takeStockCode">
                  <px-input v-model="formValue.takeStockCode" placeholder="请输入盘点编码" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点负责人" prop="takeStockPeople">
                  <px-select-v2
                    v-model="formValue.takeStockPeople"
                    filterable
                    clearable
                    :options="takeStockPeopleList"
                    placeholder="请选择盘点负责人"
                    @change="principalChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="任务计划时间" prop="planDate">
                  <px-date-picker
                    v-model="formValue.planDate"
                    type="datetimerange"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    unlink-panels
                    :disabled-date="disabledDate"
                    @change="changePlanDate"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="工具盘点列表">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="盘点范围" prop="takeStockScope">
                  <px-select
                    v-model="formValue.takeStockScope"
                    placeholder="请先选择工具所属科室"
                    :disabled="!formValue.className"
                    filterable
                    clearable
                    style="width: 100%; margin-right: 16px"
                    @change="changeTakeStockScope"
                  >
                    <px-option v-for="item in takeStockScopeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-button v-if="formValue.takeStockScope === 'choose'" type="primary" @click="dialogVisible = true">选择工具</px-button>
                <!-- <px-form-item v-if="formValue.takeStockScope === 'group'" label="盘点组" prop="groupId">
                  <px-select v-model="formValue.groupId" placeholder="请选择盘点组" filterable clearable @change="changeToolGroup">
                    <px-option v-for="item in toolGroupList" :key="item.id" :label="item.groupName" :value="item.id" />
                  </px-select>
                </px-form-item> -->
              </px-col>
            </px-row>
            <px-table :data="formValue.toolInfoDTOList" class="equip-table" :max-height="250" border>
              <px-table-column prop="toolCode" label="工具编码" min-width="160" show-overflow-tooltip />
              <px-table-column prop="toolName" label="工具名称" min-width="160" show-overflow-tooltip />
              <px-table-column prop="toolStatusDesc" label="工具状态" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <px-tag
                    effect="plain"
                    :style="{
                      color: 'rgba(0, 0, 0, 0.8)',
                      border: `1px solid ${tagBorderColorList[scope.row.toolStatus]}`,
                      backgroundColor: `${tagBgColorList[scope.row.toolStatus]}`
                    }"
                  >
                    {{ scope.row.toolStatusDesc }}
                  </px-tag>
                </template>
              </px-table-column>
              <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolUnitDesc" label="工具单位" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip />
              <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip />
              <px-table-column prop="toolPosition" label="工具位置" min-width="160" show-overflow-tooltip />
              <px-table-column fixed="right" label="操作" min-width="64" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link type="danger" icon="Delete" @click="handleDeleteTool(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="props.isDraftVisible" type="primary" @click="handleSubmit(formRef, true)">保存为草稿</px-button>
      <px-button type="primary" @click="handleSubmit(formRef, false)">保存</px-button>
    </div>
  </div>
  <!-- 选择工具弹窗 -->
  <AddSparePartsDialog :className="formValue.className" :visible="dialogVisible" @closeDialog="closeDialog" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import {
  addToolInventory,
  editToolInventory,
  getTakeStockCode,
  getToolInventory,
  queryGroupTool,
  queryToolGroupList,
  queryToolList
} from "@/api/equip/toolManage";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import AddSparePartsDialog from "./AddSparePartsDialog.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "isDraftVisible", "drawerType", "inventoryId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    takeStockName: "",
    takeStockCode: "",
    className: "",
    warehousePosition: "",
    planDate: "",
    planStartDate: "",
    planEndDate: "",
    takeStockPeople: null,
    takeStockPeopleName: "",
    remark: "",
    takeStockScope: "",
    toolInfoDTOList: [],
    isDraft: false
  },
  toolGroupList: [], // 仓库下拉框
  takeStockPeopleList: [], // 责任人下拉框
  takeStockScopeList: [
    { name: "全面盘点", value: "all" },
    { name: "指定盘点", value: "choose" }
    // { name: "按组盘点", value: "group" },
    // { name: "按类盘点", value: "type" }
  ],
  dialogVisible: false
});
const { formValue, toolGroupList, takeStockPeopleList, takeStockScopeList, dialogVisible } = toRefs(state);

const tagBorderColorList = {
  0: "#4CCBA1",
  1: "#F37272",
  2: "#F7B648",
  3: "#7997A8"
};

const tagBgColorList = {
  0: "#E8F8F3",
  1: "#FEECEC",
  2: "#FEF5E6",
  3: "#F7F7F7"
};

const handleDeleteTool = index => {
  formValue.value.toolInfoDTOList.splice(index, 1);
};

// 表单校验规则
const rules = computed(() => ({
  takeStockName: [{ required: true, message: "盘点名称不能为空", trigger: "blur" }],
  planDate: [{ required: true, message: "任务计划时间不能为空", trigger: "blur" }]
}));

// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    takeStockPeopleList.value = await getEmployeeIdAndName();
    if (props.drawerType === "add") {
      changeTakeStockScope();
      formValue.value.takeStockCode = await getTakeStockCode();
      formValue.value.takeStockName = "";
      formValue.value.className = "";
      formValue.value.warehousePosition = "";
      formValue.value.planDate = "";
      formValue.value.planStartDate = "";
      formValue.value.planEndDate = "";
      formValue.value.takeStockPeople = null;
      formValue.value.takeStockPeopleName = "";
      formValue.value.remark = "";
      formValue.value.takeStockScope = "";
      formValue.value.isDraft = false;
      delete formValue.value.id;
    } else if (props.drawerType === "edit") {
      getDetail();
    }
  } else {
    formValue.value = {
      id: "",
      takeStockName: "",
      takeStockCode: "",
      className: "",
      warehousePosition: "",
      planDate: "",
      planStartDate: "",
      planEndDate: "",
      takeStockPeople: null,
      takeStockPeopleName: "",
      remark: "",
      takeStockScope: "all",
      toolInfoDTOList: [],
      isDraft: false
    };
  }
});
// 工具盘点组
const queryToolGroup = async () => {
  toolGroupList.value = await queryToolGroupList({});
};
// 获取takeStockPeopleName
const principalChange = val => {
  const arr = takeStockPeopleList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.takeStockPeopleName = arr[0].label;
    formValue.value.principalPhone = arr[0].phone;
  }
};
// 获取计划日期开始及结束
const changePlanDate = val => {
  formValue.value.planStartDate = val[0];
  formValue.value.planEndDate = val[1];
};
// 获取范围
const changeTakeStockScope = async () => {
  formValue.value.toolInfoDTOList = [];
  if (formValue.value.takeStockScope === "all") {
    formValue.value.toolInfoDTOList = await queryToolList({ toolClassName: formValue.value.className });
  }
  //   else if (formValue.value.takeStockScope === "group") {
  //     formValue.value.groupId = "";
  //     queryToolGroup();
  //   }
};

// 获取对应盘点组的工具列表
const changeToolGroup = async val => {
  formValue.value.toolInfoDTOList = await queryGroupTool(val);
};

// 获取详情接口
const getDetail = async () => {
  formValue.value = await getToolInventory(props.inventoryId);
  const { planStartDate, planEndDate, takeStockScope } = formValue.value;
  formValue.value.planDate = [planStartDate, planEndDate];
  if (takeStockScope === "group") {
    queryToolGroup();
  }
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  formValue.value.toolInfoDTOList = formValue.value.toolInfoDTOList?.concat(val)?.filter((obj, index, self) => {
    return self.map(x => x.id).indexOf(obj.id) === index;
  });
};
// 提交
const handleSubmit = async (formEl: any, isFlag: Boolean) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.toolInfoDTOList && formValue.value.toolInfoDTOList.length > 0) {
        const arr = [];
        formValue.value.toolInfoDTOList.forEach(item => {
          arr.push(item.id);
        });
        formValue.value.toolIds = arr;
        if (isFlag) {
          formValue.value.isDraft = true;
        } else {
          formValue.value.isDraft = false;
        }
        const params = formValue.value;
        if (props.drawerType === "add") {
          await addToolInventory(params);
          PxMessage.success("创建成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editToolInventory(params);
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      } else {
        PxMessage.error("工具列表不能为空");
      }
    }
  });
};

// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  if (!isOnlyClass) {
    formValue.value.takeStockScope = "";
    formValue.value.toolInfoDTOList = [];
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
